package com.itljm.cxrMarket.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
    //需要认证的用户
    private SysUser user;
    //能够访问的权限
    private List<String> permissions;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public LoginUser(SysUser user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }
    //获取用户权限
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(ObjectUtils.isEmpty(authorities)){
            authorities = new ArrayList<>();
            if (permissions != null) {
                for (String permission : permissions) {
                    authorities.add(new SimpleGrantedAuthority(permission));
                }
            }
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    //账户是否过期，过期无法认证
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    //账号是否被锁定，锁定的用户不能通过认证
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    //过期的用户凭证（密码），是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    //是否可用，禁用的用户不能身份认证
    @Override
    public boolean isEnabled() {
        return true;
    }
}
